﻿using AoYing_DeviceCollection.Model;
using AoYing_DeviceCollection.Tools;
using MySqlX.XDevAPI.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AoYing_DeviceCollection
{
    public partial class SPIDeviceCollectionForm : Form
    {
        //SPI采集线程
        Thread spiThread;
        //AOI_2D采集线程
        Thread aoi_2DThread;
        //AOI_3D采集线程
        Thread aoi_3DThread;
        //AOI采集线程
        Thread aoiThread;
        private Socket clientSocket;
        public SPIDeviceCollectionForm()
        {
            InitializeComponent();

            BaseUtils._eventMsg.InfoHandler += EventMsg_Info;
            BaseUtils._eventMsg.ErrorMsgHandler += EventMsg_Error;
            BaseUtils._eventMsg.LogProcess = "锦飞";

            CheckForIllegalCrossThreadCalls = false; // 解除非窗口线程操作控件的限制

            // Socket开启 //实例化Socket类
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        }
        #region ListBox信息填充
        private void EventMsg_Error(object sender, EventArgs e)
        {
            try
            {
                if (LB_Error.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        WriteListBox(LB_Error, BaseUtils._eventMsg.ErrorMsg);
                    }));
                }
                else
                {
                    WriteListBox(LB_Error, BaseUtils._eventMsg.ErrorMsg);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error($"【处理失败提示出错】{ex.Message}------{ex.StackTrace}");
            }
        }

        private void EventMsg_Info(object sender, EventArgs e)
        {
            try
            {
                if (LB_Success.InvokeRequired)
                {
                    this.Invoke(new Action(() =>
                    {
                        WriteListBox(LB_Success, BaseUtils._eventMsg.Info);
                    }));
                }
                else
                {
                    WriteListBox(LB_Success, BaseUtils._eventMsg.Info);
                }
            }
            catch (Exception ex)
            {
                new LogHelper().Error($"【处理成功提示出错】{ex.Message}------{ex.StackTrace}");
            }
        }

        /// <summary>
        /// 写提示信息，同样信息不会重复生成
        /// </summary>
        /// <param name="listBox"></param>
        /// <param name="message"></param>
        private void WriteListBox(ListBox listBox, string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            if (listBox.Items.Count < 1)
            {
                listBox.Items.Insert(0, $"{DateTime.Now}-{message}");
                if (listBox.Name.Contains("Error"))
                {
                    new LogHelper().Error(message);

                }
                else
                {
                    new LogHelper().Info(message);

                }
                return;
            }
            var lastMessage = listBox.Items[0].ToString();
            if (lastMessage.Contains(message))
            {
                return;
            }

            listBox.Items.Insert(0, $"{DateTime.Now}-{message}");
            if (listBox.Name.Contains("Error"))
            {
                new LogHelper().Error(message);
            }
            else
            {
                new LogHelper().Info(message);
            }
        }
        #endregion

        #region 页面加载动作
        private void Form1_Load(object sender, EventArgs e)
        {

            try
            {
                comboBox1.SelectedIndexChanged += ComboBox1_SelectedIndexChanged;
                InitializeComboBox();
                //获取测试设备的ID信息
                DataTable dt_Deviceparameter = CommonHelper.GetDataTable($"select *  from deviceparameter where DeviceType='测试设备' and DeviceModel='Sinic-Tek-SPI';");
                if (dt_Deviceparameter != null && dt_Deviceparameter.Rows.Count > 0)
                {
                    for (int i = 0; i < dt_Deviceparameter.Rows.Count; i++)
                    {
                        CMBMachID.Items.Add(dt_Deviceparameter.Rows[i]["DeviceId"].ToString());
                    }
                }

            }
            catch (Exception ex)
            {
                BaseUtils._eventMsg.ErrorMsg = "锦飞采集Form加载异常" + ex.Message;
                MessageBox.Show("锦飞采集Form加载异常" + ex.Message);

            }
        }
        private void InitializeComboBox()
        {
            #region 设备下拉框绑定
            DataTable devicInfoDt = CommonHelper.GetDataTable($"select AreaName from  sysdatarea ;");
            // 清空ComboBox中的旧数据
            comboBox1.Items.Clear();
            // 确保DataTable中有数据后再进行绑定
            if (devicInfoDt.Rows.Count > 0)
            {
                // 遍历DataTable并将DeviceId添加到ComboBox
                foreach (DataRow row in devicInfoDt.Rows)
                {
                    comboBox1.Items.Add(row["AreaName"].ToString());
                }

                // 可选：设置ComboBox默认选中第一项
                // comboBox1.SelectedIndex = 0;
            }
            else
            {
                MessageBox.Show("未找到相关线体信息！");
            }

            #endregion
        }
        // 处理 comboBox1 选中项变化事件
        private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 获取 comboBox1 选中的值
            string selectedValue = comboBox1.SelectedItem.ToString();

            // 根据 comboBox1 选中的值来填充 comboBox2
            UpdateComboBox2(selectedValue);
        }
        private void UpdateComboBox2(string selectedValue)
        {
            DataTable devicInfoDt = CommonHelper.GetDataTable($"select SfcNo from  sfcdatwocode where Status='6' AND  AreaName='{selectedValue}';");
            // 清空ComboBox中的旧数据
            comboBox2.Items.Clear();
            // 确保DataTable中有数据后再进行绑定
            if (devicInfoDt.Rows.Count > 0)
            {
                // 遍历DataTable并将DeviceId添加到ComboBox
                foreach (DataRow row in devicInfoDt.Rows)
                {
                    comboBox2.Items.Add(row["SfcNo"].ToString());
                }

            }
            else
            {
                MessageBox.Show("未找到工单信息！");
                // InitializeComboBox();
            }

            // 默认选中 comboBox2 中的第一个值
            // comboBox2.SelectedIndex = 0;
        }
        // 处理 comboBox2 按键事件
        public void CollectionMethodAsync_1()
        {
            try
            {
                BaseUtils._eventMsg.Info = $"启动采集方法线程";
                string virtualDeviceId = ConfigurationManager.AppSettings["DeviceId"];
                string DeviceId = CMBMachID.Text;
                Thread t1 = new Thread(new ThreadStart(() =>
                {
                    while (true)
                    {
                        try
                        {
                            DataTable configDt = CommonHelper.GetDataTable($"select *  from deviceparameter where DeviceId='{DeviceId}' ;");
                            DataTable dt_machi = CommonHelper.GetDataTable($"select *  from sysdatmachine where MachID='{virtualDeviceId}' ;");
                            if (configDt.Rows.Count != 0 && dt_machi.Rows.Count != 0)
                            {
                                string virtualmachid = dt_machi.Rows[0]["MachID"].ToString();
                                string virtualmachname = dt_machi.Rows[0]["MachName"].ToString();
                                string virtualmachareaid = dt_machi.Rows[0]["AreaID"].ToString();
                                if (comboBox2.Text.Length > 0 && comboBox1.Text.Length > 0 && CMBMachID.Text.Length > 0)
                                {
                                    SmtMachine_Gather.JF_SPI_GatherSmtMachine(configDt.Rows[0], comboBox2.Text, virtualmachid, virtualmachname, virtualmachareaid);

                                }
                            }
                            else
                            {
                                MessageBox.Show("该设备id没有采集路径配置");
                            }
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                        Thread.Sleep(1000);
                    }
                }));
                t1.IsBackground = true;
                t1.Start();
                L_threads.Add(t1);
                //BaseUtils._eventMsg.Info = $"【开始采集】DeviceName：{configDt.Rows[i]["DeviceName"].ToString()} DeviceId：{configDt.Rows[i]["DeviceId"].ToString()}";
                //await Task.Run(() => SmtMachine_Gather.JF_SPI_GatherSmtMachine(configDt.Rows[i], wocode));
            }
            catch (Exception ex)
            {
                new LogHelper().Info($"采集方法出错{ex.Message}");
                BaseUtils._eventMsg.ErrorMsg = $"采集方法出错{ex.Message}";
            }


        }

        // 在TextBox1按下回车时，跳转到TextBox2
        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查是否按下了回车键
            if (e.KeyCode == Keys.Enter)
            {
                // 移动焦点到TextBox2
                //textBox2.Focus();
            }
        }
        // 在TextBox1按下回车时，跳转到TextBox2
        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            // 检查是否按下了回车键
            if (e.KeyCode == Keys.Enter)
            {
                // button1.PerformClick();
            }
        }
        #endregion

        #region 串口通信
        /// <summary>
        /// 连接服务端
        /// </summary>
        public void ConnectionServer()
        {
            // 发送用户信息: "用户名;密码"
            string userInfo = ConfigurationManager.AppSettings["UserInfo"];
            // 创建一个 TCP/IP socket
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // 远程服务端的 IP 和端口号
            string serverIp = ConfigurationManager.AppSettings["ReflowIP"];
            int serverPort = int.Parse(ConfigurationManager.AppSettings["ReflowPort"]);
            // label3.Text = serverIp;
            //label4.Text = serverPort.ToString();
            if (true)
            {
                // 判断是否连接成功
                bool connected = false;
                while (!connected)
                {
                    try
                    {
                        // 连接远程服务端 根据配置的ip 端口
                        clientSocket.Connect(serverIp, serverPort);
                        if (!clientSocket.Connected)
                        {
                            BaseUtils._eventMsg.ErrorMsg = $"【串口通信】连接失败!5分钟后尝试重连";
                            // 连接失败后等待1分钟
                            Thread.Sleep(1000 * 60 * 5);
                        }
                        else
                        {
                            connected = true; // 连接成功
                        }
                    }
                    catch (Exception ex)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【串口通信】异常: 【{ex.Message}】5分钟后尝试重连";
                        // 连接失败后等待1分钟
                        Thread.Sleep(1000 * 60 * 5);
                    }
                }
                // 连接成功后，每10秒向服务器发送字符串 GetAlarms 和 GetStates
                while (true)
                {
                    try
                    {
                        //发送用户验证信息
                        string receivedMessage = GetSocketValue(userInfo);
                        //判断用户信息校验是否成功
                        if (receivedMessage != "")
                        {
                            // 4.6 获取常用设定参数值
                            string settingParams = GetSocketValue("GetParams");
                            // 4.7 获取常用实际参数
                            string actualParams = GetSocketValue("GetStatevValues");
                            // 4.4 获取报警
                            string alarmInfo = GetSocketValue("GetAlarms");
                            // 4.8 获取辅助信息
                            string auxiliaryInfo = GetSocketValue("GetInfo");
                            // 4.10 获取产量
                            string outputStatistics = GetSocketValue("GetOutput");
                            // 4.5 获取状态信
                            string statusInfo = GetSocketValue("GetStates");
                            //4.9获取最近进板的条
                            string InputID = GetSocketValue("GetInputID");
                            //获取值插入数据库
                            StringBuilder stringBuilder = new StringBuilder();
                            stringBuilder.Append($"insert into  reflowwelding(Params,StatevValues,Alarms,Info,Output,States,InputID) " +
                                $"values('{settingParams}','{actualParams}','{alarmInfo}','{auxiliaryInfo}','{outputStatistics}','{statusInfo}','{InputID}')");
                            CommonHelper.ExeSql(stringBuilder);
                        }
                        // 每10秒发送一次数据
                        Thread.Sleep(1000 * 10);
                    }
                    catch (Exception ex)
                    {
                        BaseUtils._eventMsg.ErrorMsg = $"【串口通信】异常: 【{ex.Message}】";
                        // 发生异常后断开连接，重新连接
                        connected = false;
                        while (!connected)
                        {
                            try
                            {
                                clientSocket.Connect(serverIp, serverPort);
                                if (!clientSocket.Connected)
                                {
                                    BaseUtils._eventMsg.ErrorMsg = $"【串口通信】连接失败!5分钟后尝试重连";
                                    // 连接失败后等待1分钟
                                    Thread.Sleep(1000 * 60 * 5);
                                }
                                else
                                {
                                    connected = true;
                                }
                            }
                            catch (Exception ex1)
                            {
                                BaseUtils._eventMsg.ErrorMsg = $"【串口通信】异常: 【{ex1.Message}】5分钟后尝试重连";
                                // 连接失败后等待1分钟
                                Thread.Sleep(1000 * 60 * 5);
                            }
                        }
                    }
                }
            }

        }
        // Socket获取设备参数
        private string GetSocketValue(string strCommand)
        {
            // 回流焊Socket发送，接受设备参数存入表
            clientSocket.Send(Encoding.UTF8.GetBytes(strCommand));
            byte[] buffer = new byte[1024 * 1024 * 3];
            int len = clientSocket.Receive(buffer);
            if (len == 0)
            {
                new LogHelper().Info($"【串口通信】，回流焊命令【{strCommand}】接收失败");
                return $@"命令{strCommand}，接收失败";
            }
            var data = Encoding.Default.GetString(buffer, 0, len);
            new LogHelper().Info($"【串口通信】，回流焊命令【{strCommand}】：{data}");
            return data;
        }
        #endregion


        /// <summary>
        /// 页面关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DeviceCollectionForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            System.Environment.Exit(0);
        }

        /// <summary>
        /// FCT采集触发
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {

            ////主板SN
            //string maninSn = textBox1.Text;
            //string linkSn = textBox2.Text;
            //string messreturn = SmtMachine_Gather.FCT_GatherSmtMachine(maninSn, linkSn, comboBox1.Text);

            //if (messreturn != "执行成功")
            //{
            //    MessageBox.Show(messreturn);
            //}
            //textBox1.Clear();
            //textBox2.Clear();
            //textBox1.Focus();
        }


        /// <summary>
        /// 选择触发采集
        /// </summary>
        /// <param name="button"></param>
        /// <param name="originalText"></param>
        /// <param name="newText"></param>
        private void CommonButtonClick(Button button, string originalText, string newText)
        {
            bool state = true;
            if (button.Text == originalText)
            {
                //开启
                button.Text = newText;
                button.BackColor = Color.Red;
            }
            else
            {
                //关闭
                button.Text = originalText;
                button.BackColor = Color.White;
                state = false;
            }

            CollectionMethodAsync(button.Text.Replace("采集", "").Replace("关闭", ""), state);
        }
        /// <summary>
        /// 启动采集方法线程
        /// </summary>
        /// <param name="action">采集名</param>
        public void CollectionMethodAsync(string action, bool state)
        {
            try
            {
                switch (action)
                {
                    case "SPI":
                        if (state)
                        {
                            SmtMachine_Gather.spiState = true;
                            //SPI数据采集
                            // spiThread = new Thread(() => SmtMachine_Gather.JF_SPI_GatherSmtMachine(action));
                            spiThread.IsBackground = true;
                            spiThread.Name = "SPI数据采集";
                            spiThread.Start();

                        }
                        else
                        {
                            SmtMachine_Gather.spiState = false;
                        }
                        break;
                    case "AOI":
                    //if (state)
                    //{
                    //    SmtMachine_Gather.aoiState = true;
                    //    //AOI数据采集
                    //    aoiThread = new Thread(() => SmtMachine_Gather.AOI_SmtMachine(action));
                    //    aoiThread.IsBackground = true;
                    //    aoiThread.Name = "AOI数据采集";
                    //    aoiThread.Start();

                    //}
                    //else
                    //{
                    //    SmtMachine_Gather.aoiState = false;
                    //}
                    //break;
                    case "Feeder":
                        if (state)
                        {
                            SmtMachine_Gather.feederState = true;
                            //AOI数据采集
                            aoiThread = new Thread(() => SmtMachine_Gather.Feeder_SmtMachine(action));
                            aoiThread.IsBackground = true;
                            aoiThread.Name = "Feeder数据采集";
                            aoiThread.Start();

                        }
                        else
                        {
                            SmtMachine_Gather.feederState = false;
                        }
                        break;
                }
            }
            catch (Exception ex)
            {

                BaseUtils._eventMsg.ErrorMsg = $"采集方法出错】{ex.Message}";
            }


        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
        List<Thread> L_threads = new List<Thread>();

        private void BTNEnter_Click(object sender, EventArgs e)
        {
            if (BTNEnter.Text == "执行")
            {
                CollectionMethodAsync_1();
                CMBMachID.Enabled = false;
                comboBox1.Enabled = false;
                comboBox2.Enabled = false;
                BTNEnter.Text = "结束执行";
            }
            else
            {
                CMBMachID.Enabled = true;
                comboBox1.Enabled = true;
                comboBox2.Enabled = true;
                BTNEnter.Text = "执行";
                foreach (var item in L_threads)
                {
                    item.Abort();
                    BaseUtils._eventMsg.Info = $"终止采集线程";
                }
                L_threads.Clear();
            }
        }
    }
}
